package com.geo.geoProject.client.application;

import com.geo.geoProject.client.donneesStatiques.ApplicationGestion;


public class IPCMessage {

	///////////////////////////////////////
	////////////// SINGLETON //////////////
	///////////////////////////////////////
	private static IPCMessage sys = new IPCMessage() ;
	private IPCMessage() {}
	public static IPCMessage get() {return sys ;}
	///////////////////////////////////////
	///////////////////////////////////////
	///////////////////////////////////////
	
	public boolean transmettre(MessageInterProgramme m) {
		for (int i = 0; i < ApplicationGestion.get().listeDesProgrammes.size(); i++) {
			if (ApplicationGestion.get().listeDesProgrammes.get(i).getPid()==m.idRreceiver) {
				ApplicationGestion.get().listeDesProgrammes.get(i).recoitMessage(m) ;
				return true ;
			}
		}
		return false ;
	}

	public boolean transmettreAvecRetard(final MessageInterProgramme m, int delayInMs) {
		for (int i = 0; i < ApplicationGestion.get().listeDesProgrammes.size(); i++) {
			if (ApplicationGestion.get().listeDesProgrammes.get(i).getPid()==m.idRreceiver) {
				final Programme p = ApplicationGestion.get().listeDesProgrammes.get(i) ;
				final Runnable r = new Runnable() {
					public void run() {
						p.recoitMessage(m) ;
					}
				} ;
				ApplicationGestion.runScriptOnce(r, delayInMs) ;
				return true ;
			}
		}
		return false ;
	}
	
	public boolean transmettreNFois(final MessageInterProgramme m, int delayInMs, int N, final boolean skipFirst) {
		for (int i = 0; i < ApplicationGestion.get().listeDesProgrammes.size(); i++) {
			if (ApplicationGestion.get().listeDesProgrammes.get(i).getPid()==m.idRreceiver) {
				final Programme p = ApplicationGestion.get().listeDesProgrammes.get(i) ;
				for (int j = 0; j < N; j++) {
					final Runnable r = new Runnable() {
						public void run() {
							p.recoitMessage(m) ;
						}
					} ;
					//Window.alert(""+delayInMs*(j+1+(skipFirst?1:0))+" : "+delayInMs*(j+1+(skipFirst?1:0))) ;
					ApplicationGestion.runScriptOnce(r, delayInMs*(j+(skipFirst?1:0))) ;
				}
				return true ;
			}
		}
		return false ;
	}
	/**
	 *  rends le PID pour arreter les envois avec 'stopScript' <br>
	 *  @see ApplicationGestion.stopScript(PID) ;
	 */
	public int transmettreRepeter(final MessageInterProgramme m, int delayInMs, boolean skipFirst) {
		for (int i = 0; i < ApplicationGestion.get().listeDesProgrammes.size(); i++) {
			if (ApplicationGestion.get().listeDesProgrammes.get(i).getPid()==m.idRreceiver) {
				final Programme p = ApplicationGestion.get().listeDesProgrammes.get(i) ;
				final Runnable r = new Runnable() {
					public void run() {
						p.recoitMessage(m) ;
					}
				} ;
				int pid = ApplicationGestion.runScriptPeriodically(r, delayInMs) ;
				if (!skipFirst) {
					ApplicationGestion.runScriptOnce(r, 0) ;
				}
				return pid ;
			}
		}
		return -1 ;
	}

}
